<template>
  <el-container v-loading="loading" style="height: 100%; padding: 20px 0 20px 20px;">
    <el-aside class="page-aside" width="20%">
      <div class="aside-toolbar">
        <el-input
          v-model="filterProjectName"
          placeholder="请输入项目名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          class="aside-toolbar-search"
        />
        <el-tooltip class="item" effect="dark" content="新增" placement="top">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            :disabled="addVisible"
            style="margin-left: 10px"
            @click="addClickHandler"
          />
        </el-tooltip>
      </div>
      <div v-show="addVisible" class="aside-toolbar">
        <el-input
          ref="addInput"
          v-model.trim="addValue"
          size="small"
          prefix-icon="el-icon-plus"
          placeholder="请输入项目名称"
          :maxlength="100"
          style="flex: 1; margin-right: 10px"
        />
        <el-button-group style="width: 87px">
          <el-tooltip class="item" effect="dark" content="保存" placement="top">
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              size="small"
              :disabled="!addValue"
              @click="confirmAdd"
            />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="取消" placement="top">
            <el-button
              icon="el-icon-error"
              size="small"
              @click="cancelAdd"
            />
          </el-tooltip>
        </el-button-group>
      </div>
      <ul
        class="aside-content"
        :style="{ height: addVisible ? 'calc(100% - 77px)' : 'calc(100% - 38px)' }"
      >
        <li v-for="(item, index) in list.filter(item => item.projectName.indexOf(filterProjectName) > -1)" :key="index">
          <div
            class="aside-content-item"
            :class="{ 'active-item': item.projectName === form.projectName }"
            @click="clickAsideItemHandler(item, index)"
          >
            <span class="item-label">{{ item.projectName }}</span>
            <div class="item-toolbar">
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <el-button
                  type="danger"
                  icon="el-icon-delete-solid"
                  size="mini"
                  @click.stop="removeAsideItem(item)"
                />
              </el-tooltip>
            </div>
          </div>
        </li>
      </ul>
    </el-aside>
    <el-container>
      <el-main class="page-main">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
          <el-card class="container-card" shadow="never">
            <div slot="header">
              <el-row type="flex" align="middle">
                <el-col :span="12">
                  <span>基本信息</span>
                </el-col>
                <el-col :span="12" style="display: flex; justify-content: right">
                  <el-popover placement="bottom-end" width="300" trigger="hover">
                    <el-row type="flex" align="middle">
                      <el-col :span="12" style="text-align: center">
                        <el-button
                          icon="el-icon-download"
                          size="small"
                          :loading="downTemplateLoading"
                          @click="downloadTemplateClickHandler"
                        >下载模板</el-button>
                      </el-col>
                      <el-col :span="12" style="text-align: center">
                        <el-upload
                          ref="exportData"
                          :action="uploadUrl"
                          :headers="headers"
                          :show-file-list="false"
                          :file-list="exportFiles"
                          :on-success="exportDataSuccess"
                          accept=".xls,.xlsx"
                          :on-error="exportDataError"
                        >
                          <el-button type="primary" icon="el-icon-upload2" size="small">上传数据</el-button>
                        </el-upload>
                      </el-col>
                    </el-row>
                    <el-button slot="reference" icon="el-icon-upload" size="small">批量新增</el-button>
                  </el-popover>
                </el-col>
              </el-row>
            </div>
            <el-row>
              <el-col :span="8">
                <el-form-item label="所属集群">
                  <el-input v-model="form.clusterName" :maxlength="50" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属事业部">
                  <el-input v-model="form.divisionName" :maxlength="50" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属城市公司">
                  <el-input v-model="form.cityCorporationName" :maxlength="255" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model="form.projectName" :maxlength="100" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="第一责任人">
                  <el-input v-model="form.responsible" :maxlength="20" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目总">
                  <el-input v-model="form.projectDirector" :maxlength="20" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目经理">
                  <el-input v-model="form.projectManager" :maxlength="20" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="陪检专家">
                  <el-input v-model="form.juryExpert" :maxlength="50" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="检查日期" style="margin-bottom: 0">
                  <el-date-picker v-model="form.checkDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-divider class="hordcover-divider" content-position="left"><el-button type="primary" plain size="small" @click="addSection" icon="el-icon-plus">新增标段</el-button></el-divider>
          <el-row :gutter="20">
            <el-col :span="12" v-for="(item, index) in formList" :key="'hform' + index">
              <el-card shadow="never" style="margin-top: 20px;position: relative;">
                <i class="el-icon-delete custom-icon-close" size="mini" circle @click="removeAsideItem(item, index, true)" />
                <el-row class="card-row">
                  <el-col :span="16">
                    <el-form-item label="标段名称" style="margin-bottom: 0">
                      <el-input v-model.trim="item.sectionName" placeholder="请输入标段名称" :maxlength="20" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" />
                </el-row>
                <el-row class="card-row">
                  <el-col :span="16">
                    <el-form-item label="施工单位" style="margin-bottom: 0">
                      <el-input v-model.trim="item.constructionName" :maxlength="20" placeholder="请输入施工单位名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" />
                </el-row>
                <el-row class="card-row" :class="['label-select_' + item.fslLabelSelect]">
                  <el-col :span="16">
                    <el-form-item label="防渗漏" style="margin-bottom: 0">
                      <div style="display: flex">
                        <div class="input-box el-input el-input--small el-input-group el-input-group--prepend" style="width: 80px; flex-shrink: 0">
                          <div class="el-input-group__prepend">
                            <el-select class="label-select" v-model="item.fslLabelSelect" placeholder="等级" @change="onChangeLabel($event, item, 'avoidingSeepingLevel')">
                              <el-option label="等级" value="" />
                              <el-option label="/" value="none" />
                            </el-select>
                          </div>
                        </div>
                        <el-select class="fsl-select" v-model="item.avoidingSeepingLevel" placeholder="请选择防渗漏等级" clearable>
                          <el-option label="A级" value="A" />
                          <el-option label="B级" value="B" />
                          <el-option label="C级" value="C" />
                          <el-option label="D级" value="D" />
                        </el-select>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" class="qualified-box">
                    <el-form-item label="是否合格" style="margin-bottom: 0">
                      <el-switch v-model="item.avoidingSeepingQualified" :active-value="true" :inactive-value="false" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row class="card-row" :class="['label-select_' + item.zlLabelSelect]">
                  <el-col :span="16">
                    <el-form-item label="质量" style="margin-bottom: 0">
                      <el-input class="input-box" v-model="item.qualityScore" type="number" :max="100" @input="scoreChange(item, 'qualityScore')">
                        <el-select slot="prepend" class="label-select" v-model="item.zlLabelSelect" placeholder="得分" style="width: 80px" @change="onChangeLabel($event, item, 'qualityScore')">
                          <el-option label="得分" value="" />
                          <el-option label="/" value="none" />
                        </el-select>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" class="qualified-box">
                    <el-form-item label="是否合格" style="margin-bottom: 0">
                      <el-switch v-model="item.qualityQualified" :active-value="true" :inactive-value="false" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row class="card-row" :class="['label-select_' + item.aqwmLabelSelect]">
                  <el-col :span="16">
                    <el-form-item label="安全文明" style="margin-bottom: 0">
                      <el-input class="input-box" v-model="item.safetyConstructionScore" :max="100" type="number" @input="scoreChange(item, 'safetyConstructionScore')">
                        <el-select slot="prepend" class="label-select" v-model="item.aqwmLabelSelect" placeholder="得分" style="width: 80px" @change="onChangeLabel($event, item, 'safetyConstructionScore')">
                          <el-option label="得分" value="" />
                          <el-option label="/" value="none" />
                        </el-select>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" class="qualified-box">
                    <el-form-item label="是否合格" style="margin-bottom: 0">
                      <el-switch v-model="item.safetyConstructionQualified" :active-value="true" :inactive-value="false" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-row>
        </el-form>
      </el-main>
      <el-footer height="50">
        <preview-hardcover
          :visible.sync="previewVisible"
          :list="previewListData"
          :current="currentProject"
        />
        <div style="display: flex; justify-content: right">
          <el-button icon="el-icon-view" size="small" @click="previewClickHandler">预览生成</el-button>
          <el-button type="primary" icon="el-icon-edit" size="small" @click="confirmModify">保存</el-button>
        </div>
      </el-footer>
    </el-container>
  </el-container>
</template>

<script>
import { list, previewList, save, modify, remove, downloadTemplate } from '@/api/statement/unannouncedInspectionHardcover'
import PreviewHardcover from './components/PreviewHardcover'
import { getToken } from '@/utils/auth'
const formListItem = {
  id: '',
  sectionName: '',
  constructionName: '',
  qualityScore: '',
  qualityQualified: 0,
  avoidingSeepingLevel: null,
  avoidingSeepingQualified: 0,
  safetyConstructionScore: '',
  safetyConstructionQualified: 0,
  // 仅用于界面字段下拉
  fslLabelSelect: '',
  zlLabelSelect: '',
  aqwmLabelSelect: ''
}
export default {
  name: 'UnannouncedInspectionHardcover',
  components: {
    PreviewHardcover
  },
  data() {
    return {
      filterProjectName: '',
      list: [],
      previewListData: [],
      loading: false,
      standardForm: {
        qualifiedInterval: [80, 100],
        qualifiedLevel: ['A', 'B']
      },
      form: {

      },
      rules: {
        projectName: { required: true, message: '请输入项目名称', trigger: 'blur' }
      },
      formList: [],
      addVisible: false,
      previewVisible: false,
      addValue: '',
      downTemplateLoading: false,
      exportFiles: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/gcxt/hardcoverUnannouncedInspection/importData',
      headers: { Authorization: 'Bearer ' + getToken() },
      currentProject: {}
    }
  },
  watch: {

  },
  created() {
    this.getData()
  },
  mounted() {
  },
  methods: {
    scoreChange(item, field) {
      const val = item[field]
      if (!val) return
      if (val > 100) item[field] = 100
      else if (val < 0) item[field] = 0
      this.$forceUpdate()
    },
    getData() {
      this.loading = true
      list().then(res => {
        if (res.code === 200) {
          this.list = res.data
          if (this.currentProject.projectName && res.data.some(item => item.projectName === this.currentProject.projectName)) {
            const project = this.list.find(project => project.projectName === this.currentProject.projectName)
            this.setActiveItem(project)
          } else {
            const project = this.list.find(item => !!item.projectName)
            if (project) {
              this.setActiveItem(project)
            }
          }
        }
      }).finally(_ => {
        this.loading = false
      })

      previewList().then(res => {
        if (res.code === 200) {
          this.previewListData = res.data
        }
      })
    },
    /**
     * 筛选节点
     * @param value
     * @param data
     */
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    /**
     * 点击新增
     */
    addClickHandler() {
      this.addVisible = true
      this.$nextTick(_ => {
        this.$refs.addInput.focus()
      })
    },
    /**
     * 点击下载模板
     */
    downloadTemplateClickHandler() {
      if (this.downTemplateLoading) {
        return
      }
      this.downTemplateLoading = true
      downloadTemplate().then(file => {
        if (file) {
          const elink = document.createElement('a')
          const blob = new Blob([file])
          elink.download = '数据导入模板.xlsx'
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          // 释放URL 对象
          URL.revokeObjectURL(elink.href)
          document.body.removeChild(elink)
          this.$message.success('模板下载成功')
        } else {
          this.$message.error('模板下载失败')
        }
      }).catch(_ => {
        this.$message.error('模板下载异常')
      }).finally(_ => {
        this.downTemplateLoading = false
      })
    },
    /**
     * 导出数据成功
     * @param response
     * @param file
     * @param fileList
     */
    exportDataSuccess(response, file, fileList) {
      console.log('response：', response)
      if (response.code === 200) {
        this.getData()
        this.$refs.exportData.clearFiles()
        this.$message.success(response.msg)
      } else {
        this.$alert(response.msg, '提示', { confirmButtonText: '确定', type: 'error', center: true })
      }
    },
    /**
     * 导出数据失败
     */
    exportDataError() {
      this.$message.success('数据导出失败')
    },
    /**
     * 确认添加
     */
    confirmAdd() {
      const data = { projectName: this.addValue }
      this.loading = true
      save(data).then(res => {
        if (res.code === 200) {
          this.addVisible = false
          this.$message.success('添加成功')
          this.currentProject.projectName = this.addValue
          this.addValue = ''
          this.getData()
        } else {
          this.$message.success('添加失败，' + res.message)
        }
      }).catch(_ => {
        this.$refs.addInput.focus()
      }).finally(_ => {
        this.loading = false
      })
    },
    /**
     * 取消添加
     */
    cancelAdd() {
      this.addVisible = false
    },
    /**
     * 确认修改
     */
    confirmModify() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('是否确认修改?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.currentProject.projectName = this.form.projectName
            this.form.constructionDatas = this.formList
            save(this.form).then(res => {
              this.$message.success('修改成功')
              this.getData()
            }).catch(err => {
              this.$message.success('修改失败，' + err)
            })
          }).catch(_ => {})
        } else {
          return false
        }
      })
    },
    /**
     * 请求保存修改数据
     * @param data
     */
    requestModify(data) {
      return new Promise((resolve, reject) => {
        this.loading = true
        data.groupActionScore = data.groupActionScore || 0
        data.qualityScore = data.qualityScore || 0
        data.safetyConstructionScore = data.safetyConstructionScore || 0
        data.constructionNameScore = data.constructionNameScore || 0
        modify(data).then(res => {
          if (res.code === 200) {
            const index = this.list.findIndex(item => item.id === data.id)
            this.list[index] = res.data
            this.form = { ...res.data }
            resolve(res.data)
          } else {
            reject(res.message)
          }
        }).catch(_ => {
          reject('请求接口异常')
        }).finally(_ => {
          this.loading = false
        })
      })
    },
    /**
     * 预览
     */
    previewClickHandler() {
      const current = this.form
      if (!current.checkDate) {
        this.$message.warning('请选择检查日期！')
        return
      }
      if (!this.previewListData.length) {
        this.loading = true
        previewList().then(res => {
          if (res.code === 200) {
            this.previewListData = res.data
            this.previewVisible = true
          }
        }).finally(_ => {
          this.loading = false
        })
      } else {
        this.previewVisible = true
      }
    },
    /*
    *  新增项
    * */
    addSection() {
      this.formList.push({ ...formListItem })
    },
    /**
     * 移除
     */
    removeAsideItem(data, index, isItem = false) {
      this.$confirm('是否确认删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        if (!isItem || (isItem && data.id)) {
          const params = {}
          if (data.id) {
            params.id = data.id
          } else {
            params.projectName = data.projectName
          }
          remove({id: data.id, projectName: data.projectName}).then(res => {
            if (res.code === 200) {
              this.getData()
            }
          }).finally(_ => {
            this.loading = false
          })
        } else {
          this.formList.splice(index, 1)
          this.loading = false
        }
      }).catch(() => {

      })
    },
    /**
     * 点击右侧列表子项
     */
    clickAsideItemHandler(data, index) {
      this.setActiveItem(data)
    },
    setActiveItem(data) {
      this.form = JSON.parse(JSON.stringify(data))
      this.currentProject = JSON.parse(JSON.stringify(data))
      if (data.constructionDatas && data.constructionDatas.length) {
        const datas = JSON.parse(JSON.stringify(data.constructionDatas))
        // 初始化字段下拉
        datas.map(i => {
          const fsl = i.avoidingSeepingLevel
          const zl = i.qualityScore
          const aqwm = i.safetyConstructionScore
          i.fslLabelSelect = fsl === '/' ? 'none' : ''
          i.zlLabelSelect = zl === -1 ? 'none' : ''
          i.aqwmLabelSelect = aqwm === -1 ? 'none' : ''
        })
        this.formList = datas
      } else {
        this.formList = []
      }
    },
    onChangeLabel(label, item, field) {
      if (field === 'avoidingSeepingLevel') {
        item.avoidingSeepingQualified = false
        if (label === 'none') item[field] = '/'
        else if (label === '') item[field] = ''
      } else if (field === 'qualityScore') {
        item.qualityQualified = false
        if (label === 'none') item[field] = -1
        else if (label === '') item[field] = null
      } else if (field === 'safetyConstructionScore') {
        item.safetyConstructionQualified = false
        if (label === 'none') item[field] = -1
        else if (label === '') item[field] = null
      }
    }
  }
}
</script>

<style scoped lang="scss">
.page-aside {
  background-color: #FFF;
  margin: 0;
  padding: 0;
  .aside-toolbar {
    display:flex;
    align-items:center;
    width: 100%;
    margin-bottom: 5px;
  }
  .aside-content {
    padding: 0;
    margin: 0;
    overflow: auto;
    li{
      list-style:none
    }
    .aside-content-item {
      font-size: 14px;
      margin: 5px 0;
      padding: 0 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      cursor: pointer;
      .item-label {

      }
      .item-toolbar {
        cursor: pointer;
        margin-left: 10px;
        font-size: 12px;
        display: none;
        color: red;
      }
    }
    .active-item {
      background-color: #f5f7fa;
    }
    .aside-content-item:hover {
      background-color: #f5f7fa;
      .item-toolbar {
        display: block;
      }
    }
  }
}
.page-main {
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 20px 10px 20px;
}
  .card-row {
    margin-top: 20px;
  }
  .custom-icon-close {
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 10;
    cursor: pointer;
    color: red;
  }
  .hordcover-divider {
    margin: 40px 0 10px;
  }

.card-row {
  .fsl-select {
    flex: 1;
  }
}
// 字段为"/"时，隐藏输入框和是否合格，调整下拉框
/deep/ .label-select {
  .el-input__inner {
    text-align: center;
  }
  &_none {
    .fsl-select {
      display: none;
    }
    .input-box {
      height: 32px;
      width: 80px;
      > .el-input-group__prepend {
        border-right: 1px solid #dcdfe6;
        border-radius: 4px;
      }
      > .el-input__inner {
        display: none;
      }
    }
    .qualified-box {
      display: none;
    }
  }
}
</style>
